const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const log4jsHelper = require("./utils/log4jsHelper");

const index = require("./routes/index");
const cors = require("koa2-cors");
const koaJwt = require("koa-jwt");
const utils = require("./utils/responseUtil");

app.use(cors());
// error handler
onerror(app);

// db
require("./config/db");

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());
// app.use(logger())
app.use(require("koa-static")(__dirname + "/public"));

// logger
app.use(async (ctx, next) => {
  log4jsHelper.info(`Get 接收到的参数为: ${JSON.stringify(ctx.request.query)}`);
  log4jsHelper.info(`Post 接收到的参数为: ${JSON.stringify(ctx.request.body)}`);
  const start = new Date();
  await next().catch((err) => {
    console.log("🚀 ~ file: app.js ~ line 36 ~ awaitnext ~ err", err);
    ctx.status = 200;
    ctx.body = utils.fail("发生了错误,请重新登录", utils.CODE.AUTH_ERROR);
  });
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

app.use(
  koaJwt({
    secret: "$$!@erqwersecret",
  }).unless({ path: RegExp("/api/users/login") })
);

// routes
app.use(index.routes(), index.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  // console.error('server error', err, ctx)
  log4jsHelper.debug(err);
});

module.exports = app;
